package com.transsion.clouddemo.core.Custom.utils

import android.os.Handler
import android.os.Looper
import android.util.Log
import java.util.concurrent.Executors
import java.util.concurrent.Semaphore
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

class ThreadUtils {

    companion object {

         val HANDLER: Handler = Handler(Looper.getMainLooper())


        fun runOnUiThreadDelayed(runnable: Runnable, delayMillis: Long = 0) {
            HANDLER.postDelayed(runnable, delayMillis)
        }



        // 创建一个可调整的线程池
        var threadPool: ThreadPoolExecutor = Executors.newFixedThreadPool(10) as ThreadPoolExecutor

        // 信号量，用于控制并发任务数
        var semaphore = Semaphore(3) // 允许的最大并发任务数

        /**
         * 提交任务到线程池并控制并发任务数
         */
        fun runTaskWithConcurrencyControl(runnable: Runnable) {
            threadPool.execute {
                try {
                    semaphore.acquire() // 请求许可
                    runnable.run() // 执行任务
                } finally {
                    semaphore.release() // 释放许可
                }
            }
        }

        /**
         * 动态调整线程池线程数
         */
        fun adjustThreadPoolSize(corePoolSize: Int, maximumPoolSize: Int=2 * Runtime.getRuntime().availableProcessors()) {
            if (corePoolSize <= maximumPoolSize) {
                threadPool.corePoolSize = corePoolSize
            } else {
                return
            }
            threadPool.maximumPoolSize = maximumPoolSize
        }

        /**
         * 动态调整并发任务数
         */
        fun adjustConcurrencyLimit(concurrencyLimit: Int) {
            semaphore = Semaphore(concurrencyLimit) // 创建新的信号量
        }

        /**
         * 关闭线程池
         */
        fun shutdownThreadPool() {
            threadPool.shutdown()
            try {
                if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
                    threadPool.shutdownNow()
                }
            } catch (e: InterruptedException) {
                threadPool.shutdownNow()
            }
        }
    }



}